﻿using System;
using System.Collections.Generic;
using System.Linq;
using Business.DbConnect;
using Business.DbConnect.Constant;

namespace Business
{
    public class UserBusiness
    {
        private static QLNXeEntities db = new QLNXeEntities();

        public static user Add(user user)
        {
            try
            {
                user.password = UserService.EncodePass(user.password);
                user.roleName = RoleConstant.Member;
                user.status = "active";
                db.users.Add(user);
                //endcode pass word
                db.SaveChanges();
            }
            catch (Exception)
            {
                return null;
            }
            return user;
        }

        public static List<user> SelectList()
        {
            var users = new List<user>();
            try
            {
                users = db.users.Where(us => RoleConstant.Member.Equals(us.roleName.ToUpper())).ToList();
            }
            catch (Exception)
            {
                return users;
            }
            return users;
        }

        public static user Select(short id)
        {
            return db.users.Find(id);
        }

        public static user Update(user user)
        {
            try
            {
                user.roleName = RoleConstant.Member;
                user.status = "active";
                user current = db.users.Find(user.userID);
                if (string.IsNullOrEmpty(user.password))
                {
                    user.password = current.password;
                }
                else
                {
                    user.password = UserService.EncodePass(user.password);
                }
                user.userName = current.userName;
                db.Entry(current).CurrentValues.SetValues(user);
                db.SaveChanges();
            }
            catch (Exception)
            {
                return null;
            }

            return user;
        }

        public static bool Delete(short id)
        {
            try
            {
                user user = db.users.Find(id);
                db.users.Remove(user);
                db.SaveChanges();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }
    }
}